import { useMemberStore } from '@/stores'
// import type { Data as ResponseData } from '@/types/global'
// import type { token } from '@/types/member'
import { apiName, apiUrl } from '@/config'
import _, { reject } from 'lodash'
import { pageUrl } from '@/utils/constants'
import { ref } from 'vue'

//配置拦截器
const Interceptor = {
  //拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //拼接请求地址
    if (!options.url.startsWith('http') || !options.url.startsWith('https')) {
      // /api是系统保留的接口，不代理
      if (options.url.startsWith('/api')) {
        options.url = apiUrl + options.url
      } else {
        options.url = apiUrl + apiName + options.url
      }
    }
    //请求超时 10s
    options.timeout = 10000
    //请求头
    let sourceClient = ''
    switch (uni.getSystemInfoSync().uniPlatform) {
      case 'web':
        sourceClient = 'h5'
        break
      case 'mp-weixin':
        sourceClient = 'miniapp'
        break
      default:
        sourceClient = ''
    }
    options.header = {
      'source-client': sourceClient,
      server: true,
      'ba-user-currency': 'USD',
      'think-lang': 'en',
      ...options.header,
    }
    const memberStore = useMemberStore()
    const token = memberStore?.profile?.token || ''
    const refreshToken = memberStore.profile?.refresh_token || ''
    if (options.url.endsWith('/login/refresh')) {
      options.header['Ba-User-Refresh'] = refreshToken
    } else {
      options.header['Ba-User-Token'] = token
    }
  },
}

//拦截request请求
uni.addInterceptor('request', Interceptor)
//拦截文件上传请求
uni.addInterceptor('uploadFile', Interceptor)

//定义接口请求类型
interface Data<T> {
  msg: string
  result: T
}

const loginFail = (res: any) => {
  useMemberStore().clearProfile()
  uni.showModal({
    title: 'Reminder',
    content: 'Sign in to unlock more features. Continue?',
    confirmText: 'Sign In',
    cancelText: 'Keep Browsing',
    success: function (res) {
      if (res.confirm) {
        uni.navigateTo({ url: pageUrl['login'] })
      } else {
        uni.navigateBack()
      }
    },
  })
  return reject(res)
}

const requestLoading = ref(false)
export const request = <T>(
  options: UniApp.RequestOptions,
  showBackModal = true,
  showLoading = true,
) => {
  return new Promise<Data<T>>((resolve, reject) => {
    if (showLoading) {
      // wx.showLoading({
      //   title: 'Loading…',
      //   mask: true,
      // })
      requestLoading.value = true
    }
    uni.request({
      ...options,
      success(res) {
        wx.hideLoading()
        if (requestLoading.value) {
          wx.hideLoading()
        }

        // 检查是否收到非JSON响应或HTML页面
        try {
          if (typeof res.data === 'string' && (
              res.data.trim().startsWith('<!doctype') ||
              res.data.trim().startsWith('<html') ||
              res.data.trim().startsWith('<?xml')
            )) {
            console.error('收到HTML页面而非JSON数据', res.data.substring(0, 100));
            uni.showToast({
              title: '服务器响应格式错误，请稍后重试',
              icon: 'none',
              duration: 3000
            });
            uni.$emit('z-paging-error-emit');
            return reject(new Error('服务器返回了HTML页面而非JSON数据'));
          }
        } catch (error) {
          console.error('响应解析错误', error);
        }

        //成功
        if (res.statusCode === 200) {
          return resolve(res.data as Data<T>)
        }
        //服务器错误
        if (res.statusCode === 500) {

          if(res.data?.code === 500){
            uni.showToast({
              title: res.data?.msg,
              icon: 'none',
              duration: 3000
            });
          }

          if (requestLoading.value) {
            wx.hideLoading()
          }
          if (showBackModal) {
            uni.showModal({
              title: '',
              content: (res.data as Data<T>).msg || 'Internal server error',
              success: function (res) {
                // uni.navigateBack()
              },
            })
            uni.$emit('z-paging-error-emit')
          }

          return reject(res)
        }
        //参数错误
        if (res.statusCode === 400) {
          if (requestLoading.value) {
            wx.hideLoading()
          }
          uni.showToast({
            title: (res.data as Data<T>).msg || 'Request data exception',
            icon: 'none',
            mask: true,
            duration: 2500,
          })
          uni.$emit('z-paging-error-emit')
          return reject(res)
        }
        //登录态过期
        if (res.statusCode === 409) {
          const memberStore = useMemberStore()
          if (!memberStore.profile?.refresh_token) {
            return loginFail(res)
          }
          //通过refresh_token刷新token
          uni.request({
            url: '/login/refresh',
            method: 'POST',
            success(res) {
              if (res.statusCode != 200) {
                return loginFail(res)
              }
              //更新token
              memberStore.updateToken((res.data as Data<T>).result as any)
              //重新发起请求
              request<T>(options)
                .then((res) => {
                  return resolve(res)
                })
                .catch((err) => {
                  return reject(err)
                })
            },
            fail(err) {
              return loginFail(err)
            },
          })
        }
        //登录失效
        if (res.statusCode === 401) {
          if (requestLoading.value) {
            wx.hideLoading()
          }
          useMemberStore().clearProfile()
          return loginFail(res)
        }
      },
      //失败
      fail(err) {
        wx.hideLoading()
        if (requestLoading.value) {
          wx.hideLoading()
          requestLoading.value = false
        }

        // 更友好地处理不同类型的网络错误
        let errorMessage = 'Network request error';

        if (err && err.errMsg) {
          // 处理常见网络错误类型
          if (err.errMsg.includes('timeout')) {
            errorMessage = 'Request timed out, please check your network';
          } else if (err.errMsg.includes('failed')) {
            errorMessage = 'Connection failed, please check your network';
          }
        }

        console.error('网络请求失败:', err);

        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });

        uni.$emit('z-paging-error-emit')
        return reject(err)
      },
    })
  })
}
